package web

import (
	"html/template"
	"io/ioutil"
	"net/http"
	"os"

	"github.com/Joker/hpp"
	"github.com/Joker/jade"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/render"
	"github.com/prometheus/common/log"
)

type Jade struct {
	path  string
	goTpl *template.Template
	obj   map[string]interface{}
}

func (j *Jade) readFile() (fd []byte) {
	var fi *os.File
	var err error
	fi, err = os.Open(j.path)
	if err != nil {
		log.Error(err)
		return
	}
	defer fi.Close()
	fd, err = ioutil.ReadAll(fi)
	if err != nil {
		log.Error(err)
		return
	}
	return
}

func NewJade(path string) (j *Jade, err error) {
	j = &Jade{path: path}
	var jadeTpl string
	fi := j.readFile()
	// log.Info(string(fi))
	jadeTpl, err = jade.Parse("jade", fi)
	if err != nil {
		log.Error(err)
		return
	}
	j.goTpl, err = template.New("html").Parse(jadeTpl)
	if err != nil {
		log.Error(err)
		return
	}

	log.Infof("output:%s\n\n", hpp.PrPrint(jadeTpl))
	return
}

func (j *Jade) SetObj(obj map[string]interface{}) {
	j.obj = obj
}

func (j *Jade) ToHtml() render.HTML {
	return render.HTML{
		Template: j.goTpl,
		Name:     "",
		Data:     j.obj,
	}
}

func (j *Jade) Execute(c *gin.Context) {
	c.Render(http.StatusOK, j.ToHtml())
}
